﻿
using Castle.Core.Internal;
using Coldairarrow.Business.Interface;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.Interface;
using Coldairarrow.Util;
using Microsoft.Extensions.Options;
using NetTopologySuite.Index.HPRtree;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using org.apache.zookeeper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Net;
using System.Reflection.Metadata;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Coldairarrow.Business.Interface
{
    public class WB_OrdersStatusInterfaceBusiness : WBInterface_BaseBusiness, IJob_Business, ITransientDependency
    {
        //接口信息
        public Base_InterfaceOption WB_Query { get; set; }

        public WB_CardsInterfaceBusiness wB_CardsInterface { get; set; }
        public string SellerId { get; set; }

        public List<long> orders { get; set; }

        public WB_OrdersStatusInterfaceBusiness()
        {
            this.InterfaceName = "WB组装订单状态";
            //索引字段
            this.MapFields = GetMapField("WB_Query");

            //获取此接口的所有API信息
            this.interfaceOption = SqlDb.GetListBySql<Base_InterfaceOption>(@$"SELECT * FROM  Base_InterfaceOption(NOLOCK) WHERE Name='{InterfaceName}' ");
            WB_Query = this.interfaceOption.Where(x => x.OperateType == "WB_Query").First();

            //查询执行前的事件
            this.BeforeQueryEvent += InterfaceBusiness_BeforeQueryEvent;
            //查询执行中的事件
            this.OnQueryEvent += InterfaceBusiness_OnQueryEvent;
            //查询执行中的事件
            this.AfterQueryEvent += InterfaceBusiness_AfterQueryEvent;

            //执行非查询请求中的事件
            this.OnNoQueryEvent += InterfaceBusiness_OnNoQueryEvent;
            orders = new List<long>();
            wB_CardsInterface = new WB_CardsInterfaceBusiness();
        }

        /// <summary>
        /// 执行非查询请求中事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="LX_NoQueryEventArgs"></param>
        private void InterfaceBusiness_OnNoQueryEvent(object sender, WB_NoQueryEventArgs LX_NoQueryEventArgs)
        {
            //API请求是否成功
            LX_NoQueryEventArgs.Success = LX_NoQueryEventArgs.Result["success"].ToString().ToBool();
        }

        /// <summary>
        /// 查询执行前的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private async void InterfaceBusiness_BeforeQueryEvent(object sender, WB_QueryEventArgs queryEventArgs)
        {
            try
            {
                //设置请求头参数
                this.SqlDb._conStrings[0] = JsonSettingHelper.GetSetting("Database:BaseDb:ConnectionString");
                var auth = this.SqlDb.GetListBySql<Base_ConfigParameter>(@$"SELECT * FROM  Base_ConfigParameter(NOLOCK) WHERE Code='WB'");
                Dictionary<string, string> headers = new Dictionary<string, string>();
                headers.Add("Authorization", auth.First().Value);
                queryEventArgs.UrlQuery.Header = new Header() { Headers = headers };
                //queryEventArgs.Page.Temp1 = queryEventArgs.APINodes.Where(x => x.TargetField == "begin").First().Notes.ToInt();
                //queryEventArgs.Page.PageIndex = 1;
            }
            catch (Exception ex)
            {
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }
        }

        /// <summary>
        /// 查询中的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_OnQueryEvent(object sender, WB_QueryEventArgs queryEventArgs)
        {

            //获取请求的数据
            List<nmID> nmIDs = new List<nmID>();
            var rCount = orders.Count >= 500 ? 500 : orders.Count;
            var o = orders.Take(rCount);
            o.ForEach(x => nmIDs.Add(new nmID() { item = x }));
            WB_ReqDTO data = new WB_ReqDTO();
            data.nmIDs = nmIDs;
            queryEventArgs.reqData = GetJsonData(queryEventArgs.APINodes, queryEventArgs.ParentNode, data);

        }

        /// <summary>
        /// 查询执行后的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_AfterQueryEvent(object sender, WB_QueryEventArgs queryEventArgs)
        {

            try
            {
                //将查询后的数据转换成对应格式的数据
                WB_OrdersStatus result = (WB_OrdersStatus)JsonConvert.DeserializeObject<WB_OrdersStatus>(queryEventArgs.ResultStr);
                if (result.orders.Count > 0 && orders.Count <= 500)
                {
                    queryEventArgs.Page.Complete = true;
                }
                else
                {
                    var rCount = orders.Count >= 500 ? 500 : orders.Count;
                    orders.RemoveRange(0, rCount);
                }
                queryEventArgs.Success = true;
                queryEventArgs.Rows = result.orders;
            }
            catch (Exception ex)
            {
                queryEventArgs.Success = false;
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }

        }

        /// <summary>
        /// 执行增删改查业务
        /// </summary>
        public async void ExecuteInterface()
        {
            //获取报表代码
            List<WB_OrdersStatus.Orders> code = await this.QueryAsync<WB_OrdersStatus.Orders>(this.WB_Query, SqlDb);

        }

        /// <summary>
        /// 任务
        /// </summary>
        public void Job()
        {
            ExecuteInterface();
        }
    }

}
